/*
 * CS575 Software Design
 * Group 6
 * Group Members: Anthony Davidson, Kendra Scheesley, Lyndsey Whitman, Stephen Zakrewsky
 * Date: May 28, 2012
 * Main Author(s): Anthony Davidson
 */
package edu.drexel.cs575.a3.location;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;

import edu.drexel.cs575.a3.tax.TaxRate;
import edu.drexel.cs575.a3.tax.TaxType;

/**
 * Factory class for creating earth locations. Earthlocations are configured
 * based on the contents of specific configuration files.
 * 
 * @author anthony
 *
 */
class EarthLocationFactory implements LocationFactory {
	private static final String LOCATION = ".location";
	private static final String EARTH_TAX_DATA_PROPERTIES = "/earth-tax-data.properties";
	private static final String DOT = ".";
	private static final EarthLocationFactory instance = new EarthLocationFactory();
	private Properties taxProperties;
	
	private EarthLocationFactory() {
		try {
			taxProperties = new Properties();
			
			taxProperties.load(EarthLocationFactory.class.getResourceAsStream(EARTH_TAX_DATA_PROPERTIES));
		} catch (IOException e) {
			throw new IllegalStateException("Error while loading tax data.");
		}
	}
	
	public static EarthLocationFactory getInstance() {
		return instance;
	}
	
	@Override
	public Location createLocation(LocaleEnum localeEnum) {
		if (localeEnum == null) {
			throw new IllegalArgumentException("Locale enum cannot be null.");
		}
		
		EarthLocation earthLocation = new EarthLocation();
		
		earthLocation.setTaxRates(getTaxRatesForLocation(localeEnum));
		earthLocation.setLocaleEnum(localeEnum);
		
		return earthLocation;
	}

	private List<TaxRate> getTaxRatesForLocation(LocaleEnum localeEnum) {
		try {
			List<TaxRate> rates = new ArrayList<TaxRate>();
			Scanner scanner = new Scanner(new File(LOCATION));
			StringBuilder locationBuilder = new StringBuilder(localeEnum.toString().toLowerCase());

			//First load the national tax rate, if it exists.
			String taxValue = taxProperties.getProperty(locationBuilder.toString());
			
			if (taxValue != null) {
				rates.add(new TaxRate(TaxType.NATIONAL, Float.valueOf(taxValue)));
			}
			
			// Now load the regional rate, if any.
			// The current design only supports one region per locale. However,
			// if in the future this requirement changes, the code will only need
			// to be changed in a single location.
			if (scanner.hasNextLine()) {
				locationBuilder.append(DOT).append(scanner.nextLine());
				
				taxValue = taxProperties.getProperty(locationBuilder.toString());
				
				if (taxValue != null) {
					rates.add(new TaxRate(TaxType.REGIONAL, Float.valueOf(taxValue)));
				}
			}
			
			return rates;
		} catch (Exception e) {
			//No point in continuing if the file can't be loaded
			throw new IllegalStateException("Error loading tax rates");
		}
	}

}
